package com.gzx.spring.db.service;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.alibaba.nacos.shaded.com.google.common.collect.Sets;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzx.risk.core.pojo.*;
import com.gzx.risk.core.service.NotifyService;
import com.gzx.risk.core.service.UserLevelService;
import com.gzx.risk.core.service.WeChatService;
import com.gzx.risk.core.utils.DynamicTableImageGenerator;
import com.gzx.risk.core.utils.WechatBotKeyEnum;
import com.gzx.risk.core.utils.WechatNotificationType;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class RiskNotifyService implements NotifyService {
	@Resource
	private OrderNotifyService orderNotifyService;
	@Resource
	private PhoneUserService phoneUserService;
	@Resource
	private PhoneProductOrderService phoneProductOrderService;
	@Resource
	private WeChatService weChatService;
    @Resource
    private UserScoreResultService userScoreResultService;
    @Resource
    private RiskRuleResultService riskRuleResultService;
    @Resource
    private UserLevelService userLevelService;

    private final ObjectMapper objectMapper;

    public RiskNotifyService(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    // 以下人订单，不发通知
    private Set<String> skipUserIds = Sets.newHashSet();
    @PostConstruct
    public void init() {
        skipUserIds.add("142733199901054540");// 赵燕
        skipUserIds.add("445281199611154380");// 陈俊萍
        skipUserIds.add("232331199702202210");// 赵洪鲁
        skipUserIds.add("210727197902096937");// 吴岩
    }

	private void notify(List<String> contents) {
		List<String> users = Lists.newArrayList();
		users.add("chenjunping-gbj");
		users.add("zhaohonglu-gbj");
		weChatService.sendMessage(WechatBotKeyEnum.ORDER, WechatNotificationType.BLACK, "订单消息", users, contents);
	}

	/**
	 * 通知机器人 <br>
	 * 1、待付款<br>
	 * 2、待风控<br>
	 */
	public List<OrderInfo> findNotifyOrders() throws Exception {
		List<OrderInfo> orders = phoneProductOrderService.getOrdersByStatus(Lists.newArrayList(1));
		List<OrderInfo> results = Lists.newArrayList();
		for (OrderInfo order : orders) {
			UserInfo userInfo = phoneUserService.getUser(order.getUid());
			if (skipUserIds.contains(userInfo.getId())) {
				log.info("订单:{},忽略{}的订单，不通知", order.getOrdercode(), userInfo.getName());
				continue;
			}
			if (skipOrder(order.getParams())) {
				log.info("订单:{},忽略{}的订单，不通知", order.getOrdercode(), userInfo.getName());
				continue;
			}
            UserLevelResultInfo userLevel = userScoreResultService.getInfoByOrderCode(order.getOrdercode());
            if (userLevel == null) {
                userLevelService.rateUserScore(order.getUid().intValue(),order.getId().intValue());
                log.info("rateUserScore uid{}, oid{}", order.getUid(),order.getId());
            }
//            if ("E".equals(userLevel.getGrade()) || "D".equals(userLevel.getGrade())) {
//                log.info("订单:{},忽略{}的订单，不通知（客户等级过低)", order.getOrdercode(),userInfo.getName());
//                continue;
//            }

            Boolean isRejected = riskRuleResultService.isRejectedByIdCard(userInfo.getId());
            if (isRejected) {
                log.info("订单:{},忽略{}的订单，不通知（近30天已被拒绝）", order.getOrdercode(), userInfo.getName());
                continue;
            }

            if (orderNotifyService.isNotified(order.getOrdercode())) {
				log.info("订单:{},已经通知", order.getOrdercode());
			} else {
				results.add(order);
			}
		}
		return results;
	}

	private boolean skipOrder(String params) {
		JSONObject paramObj = JSONObject.parseObject(params);
		String id = paramObj.getString("id");
		if ("1387".equals(id)) {
			return true;
		}
		return false;
	}

	@Override
	public void notifyOrders() throws Exception {
		List<OrderInfo> orders = findNotifyOrders();
		if (orders.size() > 0) {
            exceNotify(orders);
		} else {
			log.info("无需要通知订单");
		}
	}

    @Override
    public void notifyOrder(Long orderId) throws Exception {
        OrderInfo order = phoneProductOrderService.getOrder(orderId);
        List<OrderInfo> orders = new ArrayList<>();
        orders.add(order);
        exceNotify(orders);
    }

    private void exceNotify(List<OrderInfo> orders) throws Exception {
        log.info("需要通知订单:{}", orders.size());
        List<String> contents = Lists.newArrayList();
        for (OrderInfo order : orders) {
            String status = "";
            if (order.getStatus() == 1) {
                status = "待付款";
            }
            UserInfo userInfo = phoneUserService.getUser(order.getUid());
            UserLevelResultInfo userLevel = userLevelService.getUserScoreByUid(order.getUid().toString());

            String orderTime = DateUtils.format(new Date(order.getCreatetime().longValue() * 1000),
                    "yyyy-MM-dd HH:mm");
            String machineDesc = userLevel.getMachine() == 1 ? "强制" : "非强制";
            String screenInsuranceDesc = userLevel.getScreenInsurance() == 1 ? "强制" : "非强制";
            String passRateDesc = String.format("%.2f%%", userLevel.getPassRate().multiply(new BigDecimal("100")).doubleValue());
            String minDepositDesc = String.format("%.2f元", userLevel.getMinDeposit().doubleValue());
            String prepayPeriodsDesc = userLevel.getPrepayPeriods() + "期";
            Map map = objectMapper.readValue(order.getParams(), HashMap.class);
            String title = map.get("title").toString();
            String version = map.get("version").toString();

            StringBuilder contentBuilder = new StringBuilder();
            contentBuilder.append("订单号：").append(order.getOrdercode()).append("\n");
            if (order.getStatus() == 1) {
                contentBuilder.append("待支付押金：").append(status).append("\n");
            }else{
                contentBuilder.append("状态：").append(status).append("\n");
            }
            contentBuilder.append("姓名：").append(userInfo.getName()).append("\n")
                    .append("电话：").append(userInfo.getPhone()).append("\n")
                    .append("商品名称：").append(title).append("\n")
                    .append("商品规格：").append(version).append("\n")
                    .append("订单时间：").append(orderTime).append("\n")
                    .append("客户等级：").append(userLevel.getGrade()).append("\n")
                    .append("预计通过率：").append(passRateDesc).append("\n")
                    .append("建议监管机：").append(machineDesc).append("\n")
                    .append("建议预收期数：").append(prepayPeriodsDesc).append("\n")
                    .append("建议免压额度：").append(minDepositDesc).append("\n")
                    .append("建议碎屏保障：").append(screenInsuranceDesc);
            String content = contentBuilder.toString();
            contents.add(content);
        }
        notify(contents);
        for (OrderInfo order : orders) {
            orderNotifyService.addNotified(order);
        }
    }

    /**
     * 发送每日报告通知（文本+两张图片）
     */
    @Override
    public void notifyReport() throws Exception {
        List<DailyStats> dailyStats = phoneProductOrderService.selectDailyStats();
        List<DailyTotalStats> dailyTotalStats = phoneProductOrderService.selectTotalStats();
        InputStream dSInputStream = DynamicTableImageGenerator.convertToTableImage(dailyStats, DailyStats.class);
        InputStream dTSInputStream = DynamicTableImageGenerator.convertToTableImage(dailyTotalStats, DailyTotalStats.class);
        List<String> users = Lists.newArrayList();
        users.add("chenjunping-gbj");
        users.add("wangfeng-gbj");
        weChatService.sendMessage(WechatBotKeyEnum.REPORT, WechatNotificationType.BLACK, "每日报告", users, Lists.newArrayList());
        weChatService.sendImage(WechatBotKeyEnum.REPORT, dSInputStream);
        weChatService.sendImage(WechatBotKeyEnum.REPORT, dTSInputStream);
    }

    @Override
    public void notifyReportTemp(String currentDate) throws Exception {
        InputStream images = getClass().getClassLoader().getResourceAsStream("report.temp/" + currentDate + ".png");
        if (images == null) {
            log.error("png文件为null");
            return;
        }
        List<String> users = Lists.newArrayList();
        users.add("chenjunping-gbj");
        users.add("wangfeng-gbj");
        weChatService.sendNotifyReportTemp(images, users);
    }
}
